#!/bin/bash

FINL_DIR="/pbfd/finished"
SORT_DIR="/pbfd/sort"
TRSH_DIR="/pbfd/trash"

function finished2sort(){
  find $FINL_DIR -maxdepth 1 | \
  while read dirname
  do
    dl_id=`basename $dirname`
    [ "$dl_id" == `basename $FINL_DIR` ] && continue
    log_fn="$dirname/$dl_id.log"
    [ -f "$log_fn" ] && rm -f $log_fn
    mv $dirname/* $SORT_DIR
    rmdir $dirname 2>/dev/null
  done
}

function clean_junk(){
  find $SORT_DIR | while read fn
  do
    [ -d "$fn" ] && rmdir "$fn" 2>/dev/null

    echo "$fn" | grep "\.url$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.URL$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.chm$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.mht$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.gif$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.png$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.txt$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.exe$" >/dev/null && rm -f "$fn" 2>/dev/null
    echo "$fn" | grep "\.log$" >/dev/null && rm -f "$fn" 2>/dev/null
  done
}

function format_name()
{
  echo "$1" | awk '{\
    gsub("\(720[pP]\)", "", $0);\
    gsub("\(1080[pP]\)", "", $0);\
    gsub("[\-\[]*FHD[\]\-]*", "", $0);\
    gsub("[\-\[]+HD[\]\-]+", "", $0);\
    gsub("\(www\.javhit\.com\)", "", $0);\
    gsub("\[javtorrent\.biz\]", "", $0);\
    gsub("[Jj]av\.li", "", $0);\
    gsub("javset\.com", "", $0);\
    gsub("3xplanet", "", $0);\
    gsub("www.youiv.net", "", $0);\
    gsub("24jav.net", "", $0);\
    gsub("JAVFILE\.ORG", "", $0);\
    gsub("beancom", "", $0);\
    gsub("heyzo_hd_", "HEYZO-", $0);\
    gsub("^HEY-", "HEYZO-", $0);\
    gsub("^[kK]irari *", "MKD-S");\
    \
    gsub("^[\#\-\_0-9]+", "", $0);\
    pos = match($0, "[0-9][0-9]+");\
    if (pos > 0){\
      p1 = substr($0, 1, pos-1);\
      p2 = substr($0, pos, length($0)-pos+1);\
      pos2 = match(p2, "[a-zA-Z]+");\
      if (pos2 > 0){\
        s1 = substr(p2, 1, pos2-1);\
        s2 = substr(p2, pos2, length(p2)-pos2+1);\
        if (s1 !~ /\.$/) {\
          p2 = s1"-"s2; }\
      }\
      $0 = p1"-"p2;
    }\
    gsub("--", "-", $0); gsub("--", "-", $0);\
    \
    gsub(",", "", $0);\
    gsub("^[ |	]+", "", $0);\
    gsub("[ |  ]+$", "", $0);\
    gsub("\[[ | ]+\]", "", $0);\
    gsub("\]", "] ", $0);\
    gsub("\] +", "] ", $0);\
    print toupper($0);\
  }' | awk -F"[-._ 	]" 'BEGIN{ SFX="" }{\
    if ( $0 ~ /\./ && length($NF) == 3 ) {\
      SFX = $NF;\
    }\
    if ( $1 ~ /CARIB/ ){\
      printf("%s-%s-%s", $1,$2,$3); \
    } else {\
      printf("%s-%s", $1,$2); \
    }\
    if (length(SFX) > 0){\
      printf(".%s", SFX);\
    }\
    printf("\n");\
  }'
}

function simplify_name(){
  find $SORT_DIR -maxdepth 1 |\
  while read fn
  do
    bsfn=`basename "$fn"`
    [ "$bsfn" == `basename $SORT_DIR` ] && continue
    new=`format_name "$bsfn"`
    nfn="$SORT_DIR/$new"
    [ "$fn" == "$nfn" ] && continue
    echo mv "$fn" "$nfn"
    mv "$fn" "$nfn" 
  done
}

function find_video(){
find $1 -name "*.avi" -o -name "*.AVI" \
  -o -name "*.mkv"  -o -name "*.MKV"   \
  -o -name "*.mp4"  -o -name "*.MP4"   \
  -o -name "*.wmv"  -o -name "*.WMV"   \
  -o -name "*.mpg"  -o -name "*.MPG"   \
  -o -name "*.mpeg" -o -name "*.MPEG"  \
  -o -name "*.3gp"  -o -name "*.3GP"   \
  -o -name "*.rm"   -o -name "*.RM"    \
  -o -name "*.rmvb" -o -name "*.RMVB"  \
  -o -name "*.asf"  -o -name "*.ASF"   \
  -o -name "*.divx" -o -name "*.DIVX"  \
  -o -name "*.iso"  -o -name "*.ISO" 
}

function restructure(){
  find $SORT_DIR -maxdepth 1 |\
  while read fn
  do
    [ ! -d "$fn" ] && continue
    [ `basename "$fn"` == `basename $SORT_DIR` ] && continue

    # If only one media file found in dir, move them to the sort folder
    vcnt=`find_video "$fn" | wc -l`
    if [ $vcnt -eq 1 ]
    then
      vfn=`find_video "$fn"`
      suffix=`echo "$vfn" | awk -F"." '{print toupper($NF)}'`
      mv "$vfn" "$fn"."$suffix"
      rmdir "$fn" 2>/dev/null
      [ -d "$fn" ] && mv "$fn" "$TRSH_DIR"
    fi
  done
}

function get_media_type(){
  vfn="$1"
  [ -d "$fn" ] && vfn=`find_video "$fn" | head -n 1`
  [ ! -f "$vfn" ] && echo "NUL" && return

  mediainfo "$vfn" | grep Height | \
  awk -F":" '{\
    gsub("pixels", "", $2);\
    gsub("[ |	]", "", $2);\
    print $2;\
  }' | while read ht
  do
    let ht=ht+0
    [ $ht -ge 2160 ] && echo "UHD" && return
    [ $ht -ge 1080 ] && echo "FHD" && return
    [ $ht -ge 720  ] && echo "HD" && return
    [ $ht -lt 480 ] && echo "SD" && return
    echo "NUL" && return
  done
}


function get_info(){
  vid="$1"
  htfn="./.tmp/$vid"
  [ ! -f "$htfn" ] && wget http://javfree.me/$vid -O $htfn 1>/dev/null 2>&1
  cat $htfn | grep "Published:" | grep "Posted in:" | grep "Tags:" |\
  sed 's/>/>\n/g' | sed 's/</\n</g' | awk '\
  BEGIN{ print_next = 0; tl=0; vid="'"$vid"'"}\
  ( print_next == 1 ) { \
      gsub("\[HD\] *", "", $0);\
      gsub("\[DVD\] *", "", $0);\
      tl=1; \
      if ( $0 !~ /^\[.*/ ) {\
        gsub(/^.*[0-9]+\-[0-9]+/,"["vid"]",$0);\
      }\
      printf("%s ", $0); \
      print_next=0 }\
  ( print_next == 2 ) { \
      printf("{%s}", $0); \
      print_next=0 }\
  ($0 ~ /rel=\"bookmark\"\>$/){ print_next = 1 }\
  ($0 ~ /title=\"[0-9]+/){\
      idx=index($0, /[0-9]{4}\-[0-9]{2}\-[0-9]{2}/);\
      printf("(%s) ", substr($0, idx-1, 10)) }\
  ($0 ~ /rel=\"tag\"\>/){ print_next = 2 }\
  END{ if ( tl == 0 ) { \
      printf("[%s]\n", vid) \
    } else { \
      printf("\n") } \
  }'
}

function fill_info(){
  mkdir ./.tmp 2>/dev/null
  rm -f $SORT_DIR/list.txt
  find $SORT_DIR -maxdepth 1 |\
  while read fn
  do
    [ `basename "$fn"` == `basename $SORT_DIR` ] && continue
    VID=`basename "$fn" | awk -F"[-._]" '{\
      if ( $1 ~ /CARIB/ ){\
        print $1"-"$2"-"$3; \
      } else {\
        print $1"-"$2; \
      }\
    }'`
    echo "get_info $VID"
    INFO=`get_info $VID`
    TYPE=`get_media_type $fn`
    echo "$INFO" | sed 's/\] /-'$TYPE'] /g' >> $SORT_DIR/list.txt
  done
}

#find /pbfd/sort | while read fn
#do
#  get_media_type $fn
#done
#exit 0
finished2sort
clean_junk
simplify_name
restructure
fill_info

